<?php defined('SYSPATH') or die('No direct script access.');

class Model_Item extends ORM {
	
	public function rules() {
		return array(
			'category_id' => array(
				array('not_empty'),
			),
			'name' =>array(
				array('not_empty'),
			),
			'description' =>array(
				array('not_empty'),
			),
			'price' =>array(
				array('not_empty'),
				array('decimal', array(':value', 2)),
			),
			'restock_price' => array(
				array('not_empty'),
				array('decimal', array(':value', 2))
			),
		);
	}
	
	protected $_has_many = array(
		'attributes' => array(
			'model' => 'attribute',
			'through' => 'item_attributes'
		),
		'item_attributes' => array(
			'model' => 'itemAttribute',
			'foreign_key' => 'item_id',
		),
		'inventory_items' => array(
			'model' => 'inventoryItem',
			'foreign_key' => 'item_id',
		),
		'promotions' => array(
			'model' => 'promotion',
			'through' => 'promotionitems',
		),
	);
	
	
	protected $_belongs_to = array(
		'category' => array(
			'model' => 'category',
			'foreign_key' => 'category_id',
			),
		'image' => array(
			'model' => 'image',
			'foreign_key' => 'image_id',
		),
	);
	
	public function description_has_word($keyword) {
		$description_words = explode(' ,.', $this->description);
		foreach($description_words as $desc_word) :
			if(strtolower($desc_word) == strtolower($keyword)) {
				return true;	
			}
		endforeach;
		
		return false;
	}
	
	public function in_stock(){
		$instock = false;
		
		foreach($this->inventory_items->find_all() as $item):
			if($item->quantity > 0):
				$instock = true;
			endif;
			
			if($instock):
				return true;
			else:
				return false;
			endif;
		endforeach;
	}
	
	public function active_promotions() {
		return $this->promotions
			->where('starting_date', '<', strtotime('now'))
			->and_where('ending_date', '>', strtotime('now'))
			->find_all();	
	}
	
	public function promotion_price() {
		$promotions = $this->active_promotions();
		
		$promotion_price = $this->price;
		foreach($promotions as $promotion):
			if($promotion->discount_type == 'percent') {	
				$promotion_price = (1 - ($promotion->discount / 100)) * $promotion_price;
			}
			else if($promotion->discount_type == 'amount') {
				$promotion_price = $promotion_price - $promotion->discount;	
			}
		endforeach;
		
		if($promotion_price < 0) {
			return 0;
		}
		else {
			return $promotion_price;
		}
	}
}